package com.example.artwindow.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.artwindow.domain.po.User;
import com.example.artwindow.mapper.UserMapper;
import com.example.artwindow.service.UserService;
import com.example.artwindow.service.impl.UserServiceImpl;
import com.example.artwindow.tool.JwtTool;
import com.example.artwindow.tool.TheadLocalTool;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;

@Component
@RequiredArgsConstructor
public class JwtFilter extends OncePerRequestFilter {
	private final UserService userService;

	private final UserServiceImpl userServiceImpl;
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

		String jwtToken = request.getHeader("token");
		//解析id
		Long aLong = null;
		try {
			aLong = JwtTool.parseToken(jwtToken);
		} catch (Exception ignored) {}
		if (aLong!=null){
			//获取用户
			User one = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getId, aLong));
			UserDetails userDetails = userServiceImpl.loadUserByUsername(one.getUsername());

			//将用户信息存入TheadLocal
			TheadLocalTool.setCurrentId(one.getId());
			//验证信息存入SpringSecurity
			UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(userDetails, null,userDetails.getAuthorities());
			//设置权限
			SecurityContextHolder.getContext().setAuthentication(authenticationToken);
		}
		filterChain.doFilter(request,response);
	}
}
